import time

from zz import zz_code, zz_dingtalk, zz_return, zz_log, zz_str
import requests

log = zz_log.of()


def run():
    token = zz_code.env("QMAI_TOKEN")
    token_arr = zz_str.split2(token)
    log.info(token_arr)
    if token_arr is None:
        log.error('未配置QMAI_TOKEN')
        return

    log_msg = '**蒙自源签到** \n\n'
    for item in token_arr:
        handle = Handle(item[0])

        log_msg_one = handle.run_one()
        log.info(log_msg_one)
        log_msg += log_msg_one + "\n\n"

    zz_dingtalk.send_markdown(log_msg, "蒙自源签到")


# 蒙自源
class Handle:
    def __init__(self, token):
        self.phone = None
        self.name = None
        self.token = token

    def run_one(self):
        if zz_str.is_null_or_empty(self.token):
            return "缺少参数"
        log_msg = ''
        r = self.api_user_info()
        if r.err():
            log_msg += f"{r.get_errmsg()}"
            return
        user_data = r.get_data("data")
        self.name = user_data['name']
        self.phone = user_data['mobilePhone']
        if zz_str.is_null_or_empty(self.name):
            self.name = self.phone
        log_msg = self.name + " \n"

        time.sleep(1)
        r = self.api_qian()
        log_msg += f"{r.get_errmsg()}"

        time.sleep(1)
        r = self.api_qian_check()
        fun = 0
        if r.ok():
            fun = r.get_data('data')

        log_msg += f"，积分：{fun}"
        return log_msg

    def get_headers(self):
        headers = {
            "Qm-From-Type": "catering",
            "Qm-User-Token": self.token,
            "Qm-From": 'wechat',
            "store-id": '211679',
        }
        user_agent = zz_code.env("USER_AGENT")
        if zz_str.has_any_text(user_agent):
            headers['User-Agent'] = user_agent

        return headers

    # 签到
    def api_qian(self):
        api_url = f"https://webapi.qmai.cn/web/cmk-center/sign/takePartInSign"
        headers = self.get_headers()

        post_data = {
            "activityId": '1169207686505242624',
            "appid": 'wx6cff4ec7eaabc6db',
            "mobilePhone": self.phone,
            "userName": self.name,
        }

        log.debug(api_url)
        log.debug(headers)
        log.debug(post_data)
        res = requests.post(api_url, json=post_data, headers=headers)
        r = self.to_return(res.content)

        return r

    def api_user_info(self) -> zz_return.Return:
        api_url = f"https://webapi.qmai.cn/web/catering/crm/personal-info?appid=wx6cff4ec7eaabc6db"
        headers = self.get_headers()

        log.debug(api_url)
        log.debug(headers)
        res = requests.get(api_url, headers=headers)
        r = self.to_return(res.content)

        return r

    # 查积分
    def api_qian_check(self) -> zz_return.Return:
        api_url = f"https://webapi.qmai.cn/web/catering/crm/total-points"
        headers = self.get_headers()

        post_data = {
            "appid": 'wx6cff4ec7eaabc6db',
        }

        log.debug(api_url)
        log.debug(headers)
        log.debug(post_data)
        res = requests.post(api_url, json=post_data, headers=headers)
        r = self.to_return(res.content)

        return r

    def to_return(self, content) -> zz_return.Return:
        log.debug(content)
        try:
            r = zz_return.parse(content)
            errcode = r.get_data('code')
            errmsg = r.get_data('message')
            r.set_errmsg(errmsg)
            r.set_errcode(errcode)
        except Exception as ex:
            log.error(ex)
            r = zz_return.of(123456, ex)
        log.info(f"return: {r.to_json()}")

        return r


if __name__ == '__main__':
    run()
